package cn.wzy.service.impl;

import cn.wzy.enums.BaseConstants;
import cn.wzy.mapper.EmployeeMapper;
import cn.wzy.mapper.LogininfoMapper;
import cn.wzy.mapper.ShopAuditLogMapper;
import cn.wzy.mapper.ShopMapper;
import cn.wzy.pojo.Employee;
import cn.wzy.pojo.Logininfo;
import cn.wzy.pojo.Shop;
import cn.wzy.pojo.ShopAuditLog;
import cn.wzy.results.ResponseResult;
import cn.wzy.service.ShopService;
import cn.wzy.utils.*;
import cn.wzy.vo.ApprovedVO;
import cn.wzy.vo.GoPageVo;
import cn.wzy.vo.PageVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * (Shop)表服务实现类
 *
 * @author makejava
 * @since 2023-01-09 17:52:37
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements ShopService {

    @Resource
    private EmployeeMapper employeeMapper;
    @Resource
    private MailUtils mailUtils;
    @Resource
    private RedisCache redisCache;
//    @Resource
//    private HttpServletResponse response;
    @Resource
    private HttpServletRequest request;
    @Resource
    private LogininfoMapper logininfoMapper;

    @Resource
    private ShopAuditLogMapper shopAuditLogMapper;
 public ResponseResult getShopPage(GoPageVo goPageVo) {
        Page<Shop> page = new Page<>(goPageVo.getPageIndex(),goPageVo.getPageSize());
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        if (goPageVo.getKeyword()!=null && !"".equals(goPageVo.getKeyword())){
            queryWrapper.like(Shop::getName,goPageVo.getKeyword());
        }
        List<Shop> productTypes = page(page, queryWrapper).getRecords();
        PageVo pageVo = new PageVo(productTypes, page.getTotal(), goPageVo.getPageSize());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult saveShop(Shop shop) {
        //        判断是否id存在，操作类型
        if (Objects.isNull(shop.getId())){
//            添加操作
            save(shop);
            return ResponseResult.okResult();
        }else {
//            修改操作
            updateById(shop);
            return ResponseResult.okResult();
        }
    }

    @Override
    public ResponseResult deleteShop(Long id) {
        removeById(id);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult deleteShopList(List<Long> ids) {
       removeByIds(ids);
       return ResponseResult.okResult();
    }

    /*
    * 商家入住
    * */
    @Override
    @Transactional
    public ResponseResult settlement(Shop shop) {
//        校验
        validate(shop);
//        保存 店铺信息
        shop.setRegisterTime(new Date());
        save(shop);
        //3 保存店铺管理员信息，但是如果店铺管理员原来就有店铺
        Employee admin = shop.getAdmin();
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,admin.getUsername());
        Employee employee = employeeMapper.selectOne(queryWrapper);
//        判断是否存在管理员，存在就直接管理店铺
        if (Objects.isNull(employee)){
            Long adminId = saveLoginEmployee(admin);
            shop.setAdminId(adminId);
        }else {
            shop.setAdminId(employee.getId());
        }
//        al自动审核
        //5 进行自动审核，根据审核结果需要修改店铺状态，并且添加审核日志
        String authText = shop.getName()+" "+shop.getAddress();
//        Map<String, Object> map = BaiduAuditUtils.TextCensor(authText);
//        boolean success = (boolean) map.get("success");
        boolean success = true;
        ResponseResult result =null;
        if (success){
//            result = ResponseResult.okResult(map.get("message"));
            result = ResponseResult.okResult("操作成功");
            shop.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
//            生成激活码保存到rides中
            String uuid = UUID.randomUUID().toString().replace("-","");
            System.out.println("激活码为"+uuid);
            System.out.println("商家id为"+shop.getId());
            redisCache.setCacheObject("activation_code:"+shop.getId(), uuid,30, TimeUnit.MINUTES);
//            发激活邮件
            try {
                mailUtils.complexSend("请激活","<h1><a href='http://localhost:8080/shop/activation/"+shop.getId()+"/"+uuid+"'>点击激活</a></h1>","728541855@qq.com");
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        } else{
//            result = ResponseResult.errorResult(400, (String) map.get("message"));
            result = ResponseResult.errorResult(400, "操作失败");
            shop.setState(BaseConstants.Shop.STATE_REJECT_AUDIT);
//            发失败邮件
            mailUtils.simpleSend("入住失败","失败原因："+"map.get('message')","728541855@qq.com");
        }
        updateById(shop);
//      日志
        ShopAuditLog auditLog = new ShopAuditLog();
        auditLog.setState(shop.getState()==BaseConstants.Shop.STATE_WAIT_ACTIVE?1:0);
        auditLog.setShopId(shop.getId());
        //没有审核人，因为是自动审核，但是有审核时间
        auditLog.setAuditTime(new Date());
        auditLog.setNote(shop.getState()==BaseConstants.Shop.STATE_WAIT_ACTIVE?"审核通过!":"失败,"+result.getMsg());
        shopAuditLogMapper.insert(auditLog);
        return result;
    }

    private Long saveLoginEmployee(Employee admin) {
        Logininfo logininfo = new Logininfo();
        logininfo.setUsername(admin.getUsername());
        logininfo.setPhone(admin.getPhone());
        logininfo.setEmail(admin.getEmail());
        logininfo.setType(0);
        logininfo.setDisable(1);
        String salt = UUID.randomUUID().toString().replaceAll("-","");
        String password = MD5Utils.encrypByMd5(admin.getPassword()+ salt);
        logininfo.setPassword(password);
        logininfo.setSalt(salt);
        logininfoMapper.insert(logininfo);
        admin.setSalt(salt);
        admin.setPassword(password);
        admin.setLogininfoId(logininfo.getId());
        admin.setState(BaseConstants.Employee.STATE_WAIT_AUTID);
        employeeMapper.insert(admin);
        return admin.getId();
    }

    /*
    * 激活商家
    * */
    @Override
    @Transactional
    public ResponseResult activation(Long shopId, String uuid) {
        String activationCode = redisCache.getCacheObject("activation_code:" + shopId);
        if (!StringUtils.isEmpty(activationCode)&&uuid.equals(activationCode)){
            Shop shop = getById(shopId);
            Employee employee = employeeMapper.selectById(shop.getAdminId());
            employee.setState(BaseConstants.Employee.STATE_NORMAL);
            shop.setState(BaseConstants.Shop.STATE_ACTIVE_SUCCESS);
            employeeMapper.updateById(employee);
            updateById(shop);
            //      日志
            ShopAuditLog auditLog = new ShopAuditLog();
            auditLog.setState(shop.getState()==BaseConstants.Shop.STATE_ACTIVE_SUCCESS?1:0);
            auditLog.setShopId(shop.getId());
            //没有审核人，因为是自动审核，但是有审核时间
            auditLog.setAuditTime(new Date());
            auditLog.setNote(shop.getState()==BaseConstants.Shop.STATE_ACTIVE_SUCCESS?"激活成功通过!":"激活失败失败");
            shopAuditLogMapper.insert(auditLog);
//            WebUtils.renderString(response,"激活成功");
            return ResponseResult.okResult("激活成功");
        }
//        WebUtils.renderString(response,"激活失败");
        return ResponseResult.errorResult(400,"激活失败，请联系管理员");
    }

    /*
    * 手动审核通过
    * */
    @Override
    public ResponseResult approved(ApprovedVO approvedVO) {
//       添加审核日志
//        1获取操作人
        String token = request.getHeader("token");
        Employee user = redisCache.getCacheObject("User:" + token);
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditId(user.getId());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setNote(approvedVO.getNote());
        shopAuditLog.setShopId(approvedVO.getId());
        shopAuditLog.setState(1);
        shopAuditLogMapper.insert(shopAuditLog);
//        2.修改店铺状态
        Shop shop = getById(approvedVO.getId());
        shop.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
        updateById(shop);
//        发送激活邮箱
//            生成激活码保存到rides中
        String uuid = UUID.randomUUID().toString().replace("-","");
        System.out.println("激活码为"+uuid);
        System.out.println("商家id为"+shop.getId());
        redisCache.setCacheObject("activation_code:"+shop.getId(), uuid,30, TimeUnit.MINUTES);
//            发激活邮件
        try {
            mailUtils.complexSend("请激活","<h1><a href='http://localhost:8080/shop/activation/"+shop.getId()+"/"+uuid+"'>点击激活</a></h1>","728541855@qq.com");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        return ResponseResult.okResult("审核成功");
    }

    /*
    * 手动审核失败
    * */
    @Override
    public ResponseResult auditFailed(ApprovedVO approvedVO) {
        //       添加审核日志
//        1获取操作人
        String token = request.getHeader("token");
        Employee user = redisCache.getCacheObject("User:" + token);
        ShopAuditLog shopAuditLog = new ShopAuditLog();
        shopAuditLog.setAuditId(user.getId());
        shopAuditLog.setAuditTime(new Date());
        shopAuditLog.setNote(approvedVO.getNote());
        shopAuditLog.setShopId(approvedVO.getId());
        shopAuditLog.setState(1);
        shopAuditLogMapper.insert(shopAuditLog);
        //        发送失败邮箱
        mailUtils.simpleSend("入住失败","失败原因："+shopAuditLog.getNote(),"728541855@qq.com");
        return ResponseResult.okResult("审核驳回");
    }

    //    校验
    private void validate(Shop shop) {
        //1.1 null检验
        if (shop==null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(shop.getName()))
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (shop.getAdmin()==null)
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        if (StringUtils.isEmpty(shop.getAdmin().getUsername())||
                StringUtils.isEmpty(shop.getAdmin().getPassword())|| StringUtils.isEmpty(shop.getAdmin().getComfirmPassword()))
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        //1.2 两次密码比对
        if (!shop.getAdmin().getPassword().trim().equals(shop.getAdmin().getComfirmPassword().trim()))
            throw new RuntimeException("两次密码不一致");

        //1.3 店铺是否存在
        LambdaQueryWrapper<Shop> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Shop::getName,shop.getName());
        Shop shopByDb = baseMapper.selectOne(queryWrapper);
        if (shopByDb!=null){
            throw new RuntimeException("该店铺已经存在！");
        }
    }

    @Override
    public ResponseResult getShop(Long id) {
       Shop shop = getById(id);
       return ResponseResult.okResult(shop);
    }
}

